package com.hbx.platform.auth.controller;

import com.hbx.platform.auth.Dto.LoginDto;
import com.hbx.platform.auth.context.LoginContext;
import com.hbx.platform.base.utils.AjaxResult;
import com.hbx.platform.org.domain.Employee;
import com.hbx.platform.org.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author: hbx
 * @date: 2024/04/08
 **/
@RestController
@RequestMapping("/auth")
public class AutoController {

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginDto loginDto){
        Employee employee = employeeService.queryByName(loginDto.getUsername());
        if(employee == null){
            return AjaxResult.me().setSuccess(false).setMessage("用户名或密码错误");
        }else {
            if (loginDto.getPassword().equals(employee.getPassword())) {//登陆成功
                String token = UUID.randomUUID().toString();

//                LoginContext.context.put(token,employee);//存储全局map
                //将存储全局map换为redis
                redisTemplate.opsForValue().set(token,employee);

                Map<String,Object> map = new HashMap<>();
                employee.setPassword("");//数据脱敏
                map.put("user",employee);
                map.put("token",token);
                return AjaxResult.me().setData(map).setMessage("登录成功");
            }
            return AjaxResult.me().setSuccess(false).setMessage("用户名或密码错误");
        }
    }

    @PostMapping("/logout")
    public AjaxResult logout(HttpServletRequest request){
        String token = null;
        try {
            token = request.getHeader("token");

//            LoginContext.context.remove(token);
            redisTemplate.delete(token);

            return AjaxResult.me().setMessage("退出成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("退出失败");
        }
    }

}
